import React, {useState, useEffect, useCallback} from 'react'
import {
    View,
    ScrollView,
    Alert,
    TextInput,
    TouchableOpacity,
} from 'react-native'
import {SafeAreaView} from 'react-native-safe-area-context'
import {useForm, useFieldArray, Controller} from 'react-hook-form'

import {
    Text,
    CheckBox,
    Icon,
} from '@rneui/themed'
import DateTimePicker from '@react-native-community/datetimepicker'
import AsyncStorage from '@react-native-async-storage/async-storage'
import {LeaveFormData, RegisterVO, ReasonFormData, RegisterApi, ReasonFormApi, RegisterFileApi} from '../../api/leave'
import {UserApi} from '../../api/user'
import {useLeaveDict} from '../../hooks/useDict'
import {DICT_TYPE} from '../../api/dict'
import {leaveStyles} from '../../styles/leaveStyles'
import {formatDate} from '../../utils/dateFormatter'

import {LeaderSelector, User} from '../../components/LeaderSelector'
import {RegionSelector, Region} from '../../components/RegionSelector'
import {ImageUploader, UploadedImage} from '../../components/ImageUploader'

export const LeaveAdd = ({navigation, route}: any) => {
    // 使用字典Hook获取请假相关字典数据
    const {
        getDictOptions,
        loading: dictLoading,
        error: dictError,
        refresh: refreshDict
    } = useLeaveDict()

    const {
        control,
        watch,
        setValue,
        formState: {errors}
    } = useForm<LeaveFormData>({
        defaultValues: {
            startDate: '',
            endDate: '',
            selectedReasons: [],
            destinations: [{locationType: 'domestic', destination: '', foreignAddress: ''}],
            workArrangement: '',
            remark: '',
            nextApprovers: {}
        }
    })

    const destinationsArray = useFieldArray({
        control,
        name: "destinations"
    })

    const [userInfo, setUserInfo] = useState<any>(null)
    const [showStartDatePicker, setShowStartDatePicker] = useState(false)
    const [showEndDatePicker, setShowEndDatePicker] = useState(false)
    const [nextApprovers, setNextApprovers] = useState<{ [key: string]: string[] }>({})
    const [selectedApprovers, setSelectedApprovers] = useState<{ [key: string]: User[] }>({})
    const [showLeaderSelector, setShowLeaderSelector] = useState(false)
    const [currentTaskKey, setCurrentTaskKey] = useState<string>('')
    const [showRegionSelector, setShowRegionSelector] = useState(false)
    const [currentDestinationIndex, setCurrentDestinationIndex] = useState<number>(0)
    const [_reasonDetailData, setReasonDetailData] = useState<any>(null)
    const [uploadedImages, setUploadedImages] = useState<UploadedImage[]>([])

    // 编辑模式相关状态
    const [isEditMode, setIsEditMode] = useState(false)
    const [_editData, setEditData] = useState<any>(null)
    const [_editLeaveData, setEditLeaveData] = useState<RegisterVO | null>(null)
    const [_editReasonForms, setEditReasonForms] = useState<ReasonFormData[]>([])
    const [_editAttachments, setEditAttachments] = useState<any[]>([])
    const [_editLoading, setEditLoading] = useState(false)


    // 监听表单值
    const selectedReasons = watch('selectedReasons')
    const startDate = watch('startDate')
    const endDate = watch('endDate')


    // 获取审批人用户信息
    const fetchApproverInfo = useCallback(async (approvers: { [key: string]: string[] }) => {
        try {
            const userResponse = await UserApi.getSimpleUserList()
            if (userResponse && userResponse.data) {
                const updatedSelectedApprovers: { [key: string]: User[] } = {}

                // 处理代工人 (host_sign)
                if (approvers.host_sign && approvers.host_sign.length > 0) {
                    const hostUsers = userResponse.data.filter(user =>
                        approvers.host_sign.includes(String(user.id))
                    )
                    updatedSelectedApprovers.host_sign = hostUsers
                }

                // 处理领导 (leader_sign)
                if (approvers.leader_sign && approvers.leader_sign.length > 0) {
                    const leaderUsers = userResponse.data.filter(user =>
                        approvers.leader_sign.includes(String(user.id))
                    )
                    updatedSelectedApprovers.leader_sign = leaderUsers
                }

                setSelectedApprovers(prev => ({...prev, ...updatedSelectedApprovers}))
            }
        } catch (error) {
            console.error('获取审批人用户信息失败:', error)
        }
    }, [])

    // 编辑模式下获取完整数据
    const fetchEditData = useCallback(async (leaveId: number) => {
        if (!leaveId) return

        setEditLoading(true)
        try {
            // 1. 获取请假登记详情
            const registerResponse = await RegisterApi.getRegister(leaveId)

            if (registerResponse && registerResponse.data) {
                setEditLeaveData(registerResponse.data)

                const data = registerResponse.data
                if (data.startDate) {
                    const formattedStartDate = formatDate(data.startDate)
                    if (formattedStartDate) {
                        setValue('startDate', formattedStartDate)
                    }
                }
                if (data.endDate) {
                    const formattedEndDate = formatDate(data.endDate)
                    if (formattedEndDate) {
                        setValue('endDate', formattedEndDate)
                    }
                }
                if (data.destination) {
                    // 解析目的地数据，支持国内/国外格式
                    if (data.destination.includes('|||')) {
                        // 多个目的地
                        const destinations = data.destination.split('|||').map(dest => {
                            const trimmedDest = dest.trim()
                            if (trimmedDest.startsWith('国内 /')) {
                                return {
                                    locationType: 'domestic' as const,
                                    destination: trimmedDest.substring(4).trim(),
                                    foreignAddress: ''
                                }
                            } else if (trimmedDest.startsWith('国外 /')) {
                                return {
                                    locationType: 'foreign' as const,
                                    destination: '',
                                    foreignAddress: trimmedDest.substring(4).trim()
                                }
                            } else {
                                // 兼容旧格式
                                return {
                                    locationType: 'domestic' as const,
                                    destination: trimmedDest,
                                    foreignAddress: ''
                                }
                            }
                        })
                        setValue('destinations', destinations)
                    } else {
                        // 单个目的地
                        const trimmedDest = data.destination.trim()
                        if (trimmedDest.startsWith('国内 /')) {
                            setValue('destinations', [{
                                locationType: 'domestic' as const,
                                destination: trimmedDest.substring(4).trim(),
                                foreignAddress: ''
                            }])
                        } else if (trimmedDest.startsWith('国外 /')) {
                            setValue('destinations', [{
                                locationType: 'foreign' as const,
                                destination: '',
                                foreignAddress: trimmedDest.substring(4).trim()
                            }])
                        } else {
                            // 兼容旧格式
                            setValue('destinations', [{
                                locationType: 'domestic' as const,
                                destination: data.destination,
                                foreignAddress: ''
                            }])
                        }
                    }
                }
                if (data.hostArrangement) setValue('workArrangement', data.hostArrangement)
                if (data.remark) setValue('remark', data.remark)

                // 预填充审批人信息
                const approvers: { [key: string]: string[] } = {}

                if (data.hostId) {
                    // hostId 对应领导签字，可能有多个，用逗号分隔
                    const hostIds = data.hostId.split(',').filter(id => id.trim())
                    if (hostIds.length > 0) {
                        approvers.leader_sign = hostIds
                    }
                }
                if (data.personAdmitId) {
                    // personAdmitId 对应代工人签字，可能有多个，用逗号分隔
                    const personAdmitIds = data.personAdmitId.split(',').filter(id => id.trim())
                    if (personAdmitIds.length > 0) {
                        approvers.host_sign = personAdmitIds
                    }
                }

                if (Object.keys(approvers).length > 0) {
                    setValue('nextApprovers', approvers)
                    setNextApprovers(approvers)
                    await fetchApproverInfo(approvers)
                }
            }

            // 2. 获取请假事由详情
            try {
                const reasonResponse = await ReasonFormApi.getReasonFormList(leaveId)

                if (reasonResponse && reasonResponse.data) {
                    const reasonList = reasonResponse.data
                    setEditReasonForms(reasonList)

                    // 根据事由类型设置请假类型
                    const reasonTypes = [...new Set(reasonList.map((reason: any) => reason.type).filter(Boolean))]
                    if (reasonTypes.length > 0) {
                        setValue('selectedReasons', [])
                        setTimeout(() => {
                            setValue('selectedReasons', reasonTypes)
                        }, 50)
                    }
                }
            } catch (error) {
                console.error(error)
            }

            // 3. 获取附件信息
            try {
                const attachmentResponse = await RegisterFileApi.getRegisterFile(leaveId)

                if (attachmentResponse && attachmentResponse.data) {
                    const attachmentList = attachmentResponse.data
                    setEditAttachments(attachmentList)

                    // 格式化附件数据
                    const formattedAttachments = attachmentList.map((attachment: any) => ({
                        id: attachment.id,
                        uri: attachment.leaveFileUrl,
                        url: attachment.leaveFileUrl,
                        name: attachment.leaveFileName,
                        size: attachment.leaveFileSize,
                        type: 'image/jpeg'
                    }))
                    setUploadedImages(formattedAttachments)
                }
            } catch (error) {
                console.error(error)
            }
        } catch (error) {
            console.error(error)
        } finally {
            setEditLoading(false)
        }
    }, [setValue, fetchApproverInfo])

    // 获取用户信息和初始化编辑数据
    useEffect(() => {
        const fetchUserInfo = async () => {
            try {
                const response = await UserApi.getCurrentUser()
                setUserInfo(response?.data)
            } catch (error) {
                console.error('获取用户信息失败:', error)
            }
        }
        fetchUserInfo()

        // 初始化空的图片列表
        setUploadedImages([])

        // 检查是否为编辑模式
        if (route?.params?.isEdit && route?.params?.editData) {
            setIsEditMode(true)
            setEditData(route.params.editData)

            // 获取编辑数据的完整信息
            const leaveId = route.params.editData.id
            if (leaveId) {
                fetchEditData(leaveId)
            }
        }
    }, [route?.params, setValue, fetchEditData])

    // 优化 getUserLevel 函数，使用 useCallback 避免重复创建
    const getUserLevel = useCallback(() => {
        return userInfo?.level || 0
    }, [userInfo?.level])

    // 处理地区选择
    const handleRegionSelect = useCallback((index: number) => {
        const currentDestination = destinationsArray.fields[index] as any
        // 只有国内地点才可以使用地区选择器
        if (currentDestination?.locationType === 'domestic') {
            setCurrentDestinationIndex(index)
            setShowRegionSelector(true)
        }
    }, [destinationsArray.fields])

    const handleRegionConfirm = useCallback((regions: Region[]) => {
        setShowRegionSelector(false)

        // 更新表单值
        const regionText = regions.map(region => region.name).join(' / ')
        setValue(`destinations.${currentDestinationIndex}.destination`, regionText)
    }, [currentDestinationIndex, setValue])

    // 处理地点类型切换
    const handleLocationTypeChange = useCallback((index: number, type: 'domestic' | 'foreign') => {
        setValue(`destinations.${index}.locationType`, type)
        // 清空对应的地址字段
        if (type === 'domestic') {
            setValue(`destinations.${index}.foreignAddress`, '')
        } else {
            setValue(`destinations.${index}.destination`, '')
        }
    }, [setValue])

    // 处理请假类型选择
    const handleReasonToggle = useCallback((reasonType: string | number) => {
        // 编辑模式下不需要检查日期
        if (!isEditMode && (!startDate || !endDate)) {
            Alert.alert('提示', '请先选择行程的开始日期和结束日期，然后选择请假事由')
            return
        }

        const currentReasons = selectedReasons || []
        const isRemoving = currentReasons.some(reason => String(reason) === String(reasonType))
        const newReasons = isRemoving
            ? currentReasons.filter((r: string | number) => String(r) !== String(reasonType))
            : [...currentReasons, reasonType]

        setValue('selectedReasons', newReasons)
    }, [startDate, endDate, selectedReasons, setValue, isEditMode])

    // 移除审批人
    const removeApprover = useCallback((taskKey: string, approverId: string) => {
        // 直接使用 nextApprovers 的当前值，而不是 watch
        const currentApprovers = nextApprovers[taskKey] || []
        const newApprovers = currentApprovers.filter(id => id !== approverId)
        const updatedApprovers = {...nextApprovers, [taskKey]: newApprovers}

        // 同时更新表单值和本地状态
        setValue('nextApprovers', updatedApprovers)
        setNextApprovers(updatedApprovers)

        // 同时更新selectedApprovers状态
        setSelectedApprovers(prev => {
            const currentSelectedUsers = prev[taskKey] || []
            const newSelectedUsers = currentSelectedUsers.filter(user => String(user.id) !== approverId)
            return {...prev, [taskKey]: newSelectedUsers}
        })
    }, [setValue, nextApprovers])

    // 打开审批人选择器
    const openApproverSelector = useCallback((taskKey: string) => {
        setCurrentTaskKey(taskKey)
        setShowLeaderSelector(true)
    }, [])

    // 处理审批人选择确认
    const handleApproverConfirm = useCallback((selectedUsers: User[]) => {
        const userIds = selectedUsers.map(user => String(user.id))

        // 直接使用 nextApprovers 的当前值，而不是 watch
        const updatedApprovers = {...nextApprovers, [currentTaskKey]: userIds}

        // 同时更新表单值和本地状态
        setValue('nextApprovers', updatedApprovers)
        setNextApprovers(updatedApprovers)

        // 保存选择的用户信息，用于显示姓名
        setSelectedApprovers(prev => ({...prev, [currentTaskKey]: selectedUsers}))

        setShowLeaderSelector(false)
    }, [currentTaskKey, setValue, nextApprovers])

    // 渲染下一步模块 - 使用 useCallback 优化
    const renderNextStepSection = useCallback(() => {
        const userLevel = getUserLevel()

        return (
            <View style={leaveStyles.nextStepSection}>
                <View style={leaveStyles.approvalDivider}>
                    <Text style={leaveStyles.approvalDividerText}>下一步</Text>
                    <View style={leaveStyles.approvalDividerLine}/>
                </View>

                {userLevel >= 27 && userLevel !== 100 && (
                    <View style={leaveStyles.nextStepItem}>
                        <Text style={leaveStyles.nextStepLabel}>请假期间主持工作负责人会签</Text>

                        <View style={leaveStyles.approverSelectionContainer}>
                            {nextApprovers['host_sign']?.map((approverId, index) => {
                                // 根据approverId查找对应的用户信息
                                const approver = selectedApprovers['host_sign']?.find(user => String(user.id) === approverId)
                                return (
                                    <View key={index} style={leaveStyles.selectedApprover}>
                                        <Text style={leaveStyles.selectedApproverText}>
                                            {approver?.nickname || `代工人${index + 1}`}
                                        </Text>
                                        <TouchableOpacity
                                            style={leaveStyles.removeApproverButton}
                                            onPress={() => removeApprover('host_sign', approverId)}
                                        >
                                            <Text style={leaveStyles.removeApproverText}>×</Text>
                                        </TouchableOpacity>
                                    </View>
                                )
                            })}
                        </View>

                        {/* 选择代工人按钮放在下面一行 */}
                        <TouchableOpacity
                            style={leaveStyles.selectApproverButton}
                            onPress={() => openApproverSelector('host_sign')}
                        >
                            <Icon name="add" type="material" size={16} color="white"/>
                            <Text style={leaveStyles.selectApproverButtonText}>选择代工人</Text>
                        </TouchableOpacity>

                        {(!nextApprovers['host_sign'] || nextApprovers['host_sign'].length === 0) && (
                            <Text style={leaveStyles.noApproverText}>请至少选择一名主持工作负责人</Text>
                        )}
                    </View>
                )}

                {userLevel < 27 && (
                    <View style={leaveStyles.nextStepItem}>
                        <Text style={leaveStyles.nextStepLabel}>单位负责人签字</Text>

                        <View style={leaveStyles.approverSelectionContainer}>
                            {nextApprovers['leader_sign']?.map((approverId, index) => {
                                // 根据approverId查找对应的用户信息
                                const approver = selectedApprovers['leader_sign']?.find(user => String(user.id) === approverId)
                                return (
                                    <View key={index} style={leaveStyles.selectedApprover}>
                                        <Text style={leaveStyles.selectedApproverText}>
                                            {approver?.nickname || `领导${index + 1}`}
                                        </Text>
                                        <TouchableOpacity
                                            style={leaveStyles.removeApproverButton}
                                            onPress={() => removeApprover('leader_sign', approverId)}
                                        >
                                            <Text style={leaveStyles.removeApproverText}>×</Text>
                                        </TouchableOpacity>
                                    </View>
                                )
                            })}
                        </View>

                        {/* 选择领导按钮放在下面一行 */}
                        <TouchableOpacity
                            style={leaveStyles.selectApproverButton}
                            onPress={() => openApproverSelector('leader_sign')}
                        >
                            <Icon name="add" type="material" size={16} color="white"/>
                            <Text style={leaveStyles.selectApproverButtonText}>选择领导</Text>
                        </TouchableOpacity>

                        {(!nextApprovers['leader_sign'] || nextApprovers['leader_sign'].length === 0) && (
                            <Text style={leaveStyles.noApproverText}>请至少选择一名单位负责人</Text>
                        )}
                    </View>
                )}
            </View>
        )
    }, [getUserLevel, selectedApprovers, nextApprovers, removeApprover, openApproverSelector])

    return (
        <View style={leaveStyles.container}>
            <ScrollView contentContainerStyle={leaveStyles.formContainer}>
                {/* 开始日期 */}
                <Text style={leaveStyles.title}>广西大学请示请假报告登记表</Text>
                <View style={leaveStyles.fieldContainer}>

                    <Text style={leaveStyles.label}>开始日期</Text>
                    <Controller
                        control={control}
                        name="startDate"
                        rules={{
                            required: "请选择开始日期",
                            validate: (value) => {
                                if (!value) return "请选择开始日期"
                                const selectedDate = new Date(value)
                                const today = new Date()
                                today.setHours(0, 0, 0, 0)
                                return selectedDate >= today || "开始日期不能早于今天"
                            }
                        }}
                        render={({field: {onChange: _onChange, value}}) => (
                            <View>
                                <TouchableOpacity
                                    style={leaveStyles.dateButton}
                                    onPress={() => setShowStartDatePicker(true)}
                                >
                                    <Text style={leaveStyles.dateButtonText}>
                                        {value || '请选择开始日期'}
                                    </Text>
                                </TouchableOpacity>
                                {showStartDatePicker && (
                                    <DateTimePicker
                                        value={value ? new Date(value) : new Date()}
                                        mode="date"
                                        display="default"
                                        minimumDate={new Date()}
                                        onChange={(event, selectedDate) => {
                                            setShowStartDatePicker(false)
                                            if (selectedDate) {
                                                _onChange(selectedDate.toISOString().split('T')[0])
                                            }
                                        }}
                                    />
                                )}
                            </View>
                        )}
                    />
                    {errors.startDate && (
                        <Text style={leaveStyles.errorText}>{errors.startDate.message}</Text>
                    )}
                </View>

                {/* 结束日期 */}
                <View style={leaveStyles.fieldContainer}>
                    <Text style={leaveStyles.label}>结束日期</Text>
                    <Controller
                        control={control}
                        name="endDate"
                        rules={{
                            required: "请选择结束日期",
                            validate: (value) => {
                                if (!startDate) return "请先选择开始日期"
                                if (!value) return "请选择结束日期"
                                const start = new Date(startDate)
                                const end = new Date(value)
                                return end >= start || "结束日期不能早于开始日期"
                            }
                        }}
                        render={({field: {onChange: _onChange, value}}) => (
                            <View>
                                <TouchableOpacity
                                    style={leaveStyles.dateButton}
                                    onPress={() => setShowEndDatePicker(true)}
                                >
                                    <Text style={leaveStyles.dateButtonText}>
                                        {value || '请选择结束日期'}
                                    </Text>
                                </TouchableOpacity>
                                {showEndDatePicker && (
                                    <DateTimePicker
                                        value={value ? new Date(value) : new Date()}
                                        mode="date"
                                        display="default"
                                        minimumDate={startDate ? new Date(startDate) : new Date()}
                                        onChange={(event, selectedDate) => {
                                            setShowEndDatePicker(false)
                                            if (selectedDate) {
                                                _onChange(selectedDate.toISOString().split('T')[0])
                                            }
                                        }}
                                    />
                                )}
                            </View>
                        )}
                    />
                    {errors.endDate && (
                        <Text style={leaveStyles.errorText}>{errors.endDate.message}</Text>
                    )}
                </View>

                {/* 请假事由 */}
                <Text style={leaveStyles.label}>请选择请假类型</Text>
                {(() => {
                    const leaveTypeOptions = getDictOptions(DICT_TYPE.LEAVE_TYPE)

                    // 如果字典正在加载，显示加载状态
                    if (dictLoading) {
                        return (
                            <View style={leaveStyles.reasonContainer}>
                                <Text style={leaveStyles.loadingText}>
                                    正在加载请假类型...
                                </Text>
                            </View>
                        )
                    }

                    // 如果加载出错或没有数据，显示错误信息和重试按钮
                    if (dictError || !leaveTypeOptions || leaveTypeOptions.length === 0) {
                        return (
                            <View style={leaveStyles.reasonContainer}>
                                <Text style={leaveStyles.errorText}>
                                    {dictError || '暂无请假类型数据'}
                                </Text>
                                <TouchableOpacity
                                    style={leaveStyles.retryButton}
                                    onPress={() => refreshDict()}
                                >
                                    <Text style={leaveStyles.retryButtonText}>点击重试</Text>
                                </TouchableOpacity>
                            </View>
                        )
                    }

                    // 正常渲染请假类型选项
                    return leaveTypeOptions.map(option => {
                        const isChecked = selectedReasons?.some(reason =>
                            String(reason) === String(option.value)
                        ) || false

                        return (
                            <View key={option.value} style={leaveStyles.reasonContainer}>
                                <CheckBox
                                    title={option.label}
                                    checked={isChecked}
                                    onPress={() => handleReasonToggle(option.value as string | number)}
                                    containerStyle={leaveStyles.checkboxContainer}
                                />
                            </View>
                        )
                    })
                })()}

                {/* 目的地列表 */}
                <View style={leaveStyles.fieldContainer}>
                    <Text style={leaveStyles.label}>前往地点</Text>
                    {destinationsArray.fields.map((field, index) => (
                        <View key={field.id} style={leaveStyles.arrayItem}>
                            {/* 国内/国外选择 */}
                            <Controller
                                control={control}
                                name={`destinations.${index}.locationType`}
                                render={({field: {onChange, value}}) => (
                                    <View style={leaveStyles.checkboxRow}>
                                        <CheckBox
                                            title="国内"
                                            checked={value === 'domestic'}
                                            onPress={() => {
                                                onChange('domestic')
                                                handleLocationTypeChange(index, 'domestic')
                                            }}
                                            containerStyle={leaveStyles.checkboxContainer}
                                            checkedIcon="dot-circle-o"
                                            uncheckedIcon="circle-o"
                                        />
                                        <CheckBox
                                            title="国外"
                                            checked={value === 'foreign'}
                                            onPress={() => {
                                                onChange('foreign')
                                                handleLocationTypeChange(index, 'foreign')
                                            }}
                                            containerStyle={leaveStyles.checkboxContainer}
                                            checkedIcon="dot-circle-o"
                                            uncheckedIcon="circle-o"
                                        />
                                    </View>
                                )}
                            />

                            {/* 地址输入区域 */}
                            <Controller
                                control={control}
                                name={`destinations.${index}.locationType`}
                                render={({field: {value: locationType}}) => (
                                    <>
                                        {locationType === 'domestic' ? (
                                            <Controller
                                                control={control}
                                                name={`destinations.${index}.destination`}
                                                rules={{required: "请选择前往地点"}}
                                                render={({field: {onChange: _onChange, value}}) => (
                                                    <TouchableOpacity
                                                        style={leaveStyles.regionSelector}
                                                        onPress={() => handleRegionSelect(index)}
                                                    >
                                                        <Text style={[
                                                            leaveStyles.regionSelectorText,
                                                            !value && leaveStyles.regionSelectorPlaceholder
                                                        ]}>
                                                            {value || '请选择国内地点'}
                                                        </Text>
                                                        <Icon name="location-on" type="material" size={20}
                                                              color="#666"/>
                                                    </TouchableOpacity>
                                                )}
                                            />
                                        ) : (
                                            <Controller
                                                control={control}
                                                name={`destinations.${index}.foreignAddress`}
                                                rules={{required: "请输入国外地址"}}
                                                render={({field: {onChange: _onChange, value}}) => (
                                                    <TextInput
                                                        style={leaveStyles.textInput}
                                                        value={value}
                                                        onChangeText={_onChange}
                                                        placeholder="请输入国家和详细地址"
                                                        multiline={true}
                                                        numberOfLines={3}
                                                        textAlignVertical="top"
                                                    />
                                                )}
                                            />
                                        )}
                                    </>
                                )}
                            />

                            {destinationsArray.fields.length > 1 && (
                                <View style={leaveStyles.deleteButtonContainer}>
                                    <Icon
                                        name="close"
                                        type="material"
                                        size={20}
                                        color="white"
                                        containerStyle={leaveStyles.circularDeleteButton}
                                        onPress={() => destinationsArray.remove(index)}
                                    />
                                </View>
                            )}
                        </View>
                    ))}
                    <View style={leaveStyles.addButtonContainer}>
                        <TouchableOpacity
                            style={leaveStyles.circularAddButton}
                            onPress={() => destinationsArray.append({
                                locationType: 'domestic',
                                destination: '',
                                foreignAddress: ''
                            })}
                        >
                            <Icon
                                name="add"
                                type="material"
                                size={20}
                                color="white"
                            />
                        </TouchableOpacity>
                    </View>
                </View>

                {/* 请假期间主持工作负责人安排 */}
                {getUserLevel() >= 27 && getUserLevel() !== 100 && (
                    <View style={leaveStyles.fieldContainer}>
                        <Text style={leaveStyles.label}>请假期间主持工作负责人安排</Text>
                        <Controller
                            control={control}
                            name="workArrangement"
                            render={({field: {onChange: _onChange, value}}) => (
                                <TextInput
                                    style={leaveStyles.textArea}
                                    value={value}
                                    onChangeText={_onChange}
                                    placeholder="请输入请假期间工作安排..."
                                    multiline={true}
                                    numberOfLines={3}
                                    textAlignVertical="top"
                                />
                            )}
                        />
                    </View>
                )}

                {/* 备注 */}
                <View style={leaveStyles.fieldContainer}>
                    <Text style={leaveStyles.label}>备注</Text>
                    <Controller
                        control={control}
                        name="remark"
                        render={({field: {onChange: _onChange, value}}) => (
                            <TextInput
                                style={leaveStyles.textArea}
                                value={value}
                                onChangeText={_onChange}
                                placeholder="请输入备注..."
                                multiline={true}
                                numberOfLines={3}
                                textAlignVertical="top"
                            />
                        )}
                    />
                </View>

                {/* 图片上传 */}
                <View style={leaveStyles.fieldContainer}>
                    <Text style={leaveStyles.label}>上传图片</Text>
                    <ImageUploader
                        images={uploadedImages}
                        onImagesChange={setUploadedImages}
                        maxImages={5}
                        maxSize={1}
                        allowedFormats={['.jpg', '.jpeg', '.png']}
                        showPreview={true}
                        imageSize={80}
                        directory="leave"
                    />
                </View>
                {/* </Card> */}

                {/* 审批意见模块 */}
                {/* {renderApprovalSection()} */}

                {/* 下一步模块 */}
                {renderNextStepSection()}

                {/* 已选择的请假事由状态 */}
                <View style={leaveStyles.selectedReasonsContainer}>
                    {selectedReasons && selectedReasons.length > 0 && startDate && endDate ? (
                        <>
                            <TouchableOpacity
                                style={leaveStyles.confirmButton}
                                onPress={() => {
                                    // 获取当前表单数据
                                    const currentFormData = watch()

                                    navigation.navigate('LeaveReasonDetail', {
                                        selectedReasons: selectedReasons,
                                        startDate: startDate,
                                        endDate: endDate,
                                        onSave: async (reasonData: any) => {
                                            setReasonDetailData(reasonData)
                                            // 清空相关的草稿数据
                                            try {
                                                const reasonTypes = selectedReasons.sort().join('_')
                                                const draftKey = `leave_reason_detail_${reasonTypes}_${startDate}_${endDate}`
                                                await AsyncStorage.removeItem(draftKey)
                                            } catch (error) {
                                                console.error(error)
                                            }
                                            if (!isEditMode) {
                                                // 新增模式下清空表单
                                                setValue('destinations', [{
                                                    locationType: 'domestic',
                                                    destination: '',
                                                    foreignAddress: ''
                                                }])
                                                setValue('workArrangement', '')
                                                setValue('remark', '')
                                                setValue('selectedReasons', [])
                                                setValue('startDate', '')
                                                setValue('endDate', '')
                                                setNextApprovers({
                                                    leader_sign: [],
                                                    host_sign: [],
                                                })
                                                setUploadedImages([])
                                            }
                                        },
                                        // 传递主请假申请数据
                                        mainLeaveData: {
                                            level: userInfo?.level || 0,
                                            destinations: currentFormData.destinations?.map(d => {
                                                if (d.locationType === 'domestic') {
                                                    return `国内 / ${d.destination}`
                                                } else {
                                                    return `国外 / ${d.foreignAddress}`
                                                }
                                            }) || [],
                                            workArrangement: currentFormData.workArrangement || '',
                                            remark: currentFormData.remark || '',
                                            hostId: nextApprovers.leader_sign?.join(',') || '',  // 选择领导 → hostId，多个用逗号分隔
                                            personId: userInfo?.id || undefined,
                                            personAdmitId: nextApprovers.host_sign?.join(',') || '',  // 代工人 → personAdmitId，多个用逗号分隔
                                            deptId: userInfo?.deptIds?.[0] || undefined,
                                            uploadedImages: uploadedImages, // 传递上传的图片
                                            registerId: isEditMode ? _editLeaveData?.id : undefined, // 编辑模式下的请假登记ID
                                        },
                                        // 编辑模式下传递已有的请假事由详情数据
                                        editReasonData: isEditMode ? _editReasonForms : undefined
                                    })
                                }}
                            >
                                <Text style={leaveStyles.confirmButtonText}>
                                    {isEditMode ? '更新' : '确定'}
                                </Text>
                            </TouchableOpacity>
                            <Text style={leaveStyles.selectedReasonsText}>
                                已经选中 {selectedReasons.length} 种请假类型
                            </Text>
                        </>
                    ) : (
                        <>
                            <Text style={leaveStyles.selectedReasonsText}>
                                请先选择请假类型和日期
                            </Text>
                            <TouchableOpacity
                                style={[leaveStyles.confirmButton, leaveStyles.disabledOpacity]}
                                disabled={true}
                            >
                                <Text style={leaveStyles.confirmButtonText}>
                                    {isEditMode ? '更新' : '确定'}
                                </Text>
                            </TouchableOpacity>
                        </>
                    )}
                </View>
            </ScrollView>

            {/* 审批人选择器 */}
            <LeaderSelector
                visible={showLeaderSelector}
                onClose={() => setShowLeaderSelector(false)}
                onConfirm={handleApproverConfirm}
                multiple={true}
                title={currentTaskKey === 'host_sign' ? '选择代工人' : '选择领导'}
                selectedUserIds={nextApprovers[currentTaskKey] || []}
                showDeptFilter={true}
                deptId={userInfo?.deptIds}
                currentUserId={userInfo?.id}
            />

            {/* 地区选择器 */}
            <RegionSelector
                visible={showRegionSelector}
                onClose={() => setShowRegionSelector(false)}
                onConfirm={handleRegionConfirm}
                title="选择前往地点"
            />

        </View>
    )
}
